<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon icon="material-symbols:close" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                ifShow: () => {
                  return record.displayAlarmActivity;
                },
                icon: 'icon-park-outline:transaction-order',
                tooltip: {
                  title: '活动',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                ifShow: () => {
                  return record.displayDetailedAlarmInformation;
                },
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                ifShow: () => {
                  return record.AllowConfirmationAlarms;
                },
                icon: 'ion:checkmark-sharp',
                tooltip: {
                  title: '应答',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
              {
                ifShow: () => {
                  return record.AllowClearingNotifications;
                },
                icon: 'material-symbols:close',
                tooltip: {
                  title: '清除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" setup>
  import { Alert, Tooltip } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import { onMounted, nextTick, ref, watch } from 'vue';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useWebSocket } from '@vueuse/core';

  //websocket链接
  const wsUrl = `ws://${import.meta.env.VITE_IP_PORT}/api/ws/plugins/telemetry?token=`
  const token: any = localStorage.getItem('jwt_token');

  // 获取 表单数据
  const props = defineProps({
    widgetData: {
      type: Object,
    },
    isResize: {
      type: Boolean,
    },
    dashboard: {
      type: Boolean,
    },
    formData: {
      type: Object,
    },
  });

  const searchFormSchema: FormSchema[] = [
    {
      field: 'deptName',
      label: '',
      componentProps: () => {
        return {
          placeholder: '输入搜索关键字',
        };
      },
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  // 模拟表头
  const columns: BasicColumn[] = [
    {
      title: '模拟表头1',
      dataIndex: 'AnalogHeader1',
      width: 160,
      align: 'left',
      sorter: true,
    },
    {
      title: '模拟表头2',
      dataIndex: 'AnalogHeader2',
      width: 160,
      sorter: true,
    },
    {
      title: '模拟表头3',
      dataIndex: 'AnalogHeader3',
      width: 160,
      sorter: true,
    },
    {
      title: '模拟表头4',
      dataIndex: 'AnalogHeader4',
      width: 160,
      sorter: true,
    },
    {
      title: '模拟表头5',
      dataIndex: 'AnalogHeader5',
      width: 160,
      sorter: true,
    },
    {
      title: '模拟表头6',
      dataIndex: 'AnalogHeader6',
      width: 160,
      sorter: true,
    },
  ];

  let tableAction = ref<any>({
    displayAlarmActivity: false,
    displayDetailedAlarmInformation: false,
    AllowAllocationAlarms: false,
    AllowConfirmationAlarms: false,
    AllowClearingNotifications: false,
  });

  let isHaveTableAction = ref<boolean>(false);

  //模拟表格数据
  const tableData = ref<Array<any>>([
    {
      AnalogHeader1: '模拟数据1',
      AnalogHeader2: '模拟数据2',
      AnalogHeader3: '模拟数据3',
      AnalogHeader4: '模拟数据4',
      AnalogHeader5: '模拟数据5',
      AnalogHeader6: '模拟数据6',
    },
    {
      AnalogHeader1: '模拟数据1',
      AnalogHeader2: '模拟数据2',
      AnalogHeader3: '模拟数据3',
      AnalogHeader4: '模拟数据4',
      AnalogHeader5: '模拟数据5',
      AnalogHeader6: '模拟数据6',
    },
  ]);

  const { createConfirm } = useMessage();

  watch(
    () => props.formData,
    (nVal: any) => {
      if (nVal === undefined || nVal === null) {
        return;
      }
      let columns: BasicColumn[] = [];
      let alarmFields: Array<any> = [];

      nVal.formOption.alarmColumns.forEach((item) => {
        alarmFields.push({
          type: 'ALARM_FIELD',
          key: item.label,
        });

        columns.push({
          title: item.value,
          dataIndex: item.value,
          width: 160,
          sorter: true,
        });
      });
      let dataSource: Array<any> = [];

      let sendParams: any = {
        attrSubCmds: [],
        tsSubCmds: [],
        historyCmds: [],
        entityDataCmds: [],
        entityDataUnsubscribeCmds: [],
        alarmDataCmds: [
          {
            query: {
              entityFilter: {
                type: 'singleEntity',
                singleEntity: {
                  entityType: 'DEVICE',
                  id: '03b2b070-fd4f-11ee-bf35-41a6f6398a5e',
                },
              },
              pageLink: {
                page: 0,
                pageSize: 10,
                textSearch: null,
                typeList: [],
                severityList: [],
                statusList: [],
                searchPropagatedAlarms: false,
                sortOrder: {
                  key: {
                    key: 'createdTime',
                    type: 'ALARM_FIELD',
                  },
                  direction: 'DESC',
                },
                startTs: 1712468546296,
                endTs: 1715060546296,
              },
              alarmFields: alarmFields,
              entityFields: [],
              latestValues: [],
            },
            cmdId: 1,
          },
        ],
        alarmDataUnsubscribeCmds: [],
        entityCountCmds: [],
        entityCountUnsubscribeCmds: [],
        alarmCountCmds: [],
        alarmCountUnsubscribeCmds: [],
      };

      const { data, send } = useWebSocket(`${wsUrl}${token}`, {
        autoClose: false,
        autoReconnect: false,
        heartbeat: false,
        onMessage: () => {
          let res = JSON.parse(data.value);

          dataSource = res.data.data;

          setProps({
            title: nVal.formOption.tableTitle,
            columns: columns,
            dataSource: dataSource,
          });
          if (nVal.formOption.tabletype === 'ALARMS_TABLE') {
            Object.keys(tableAction.value).forEach((key) => {
              let flag = true;
              nVal.formOption.buttonFunction.forEach((item) => {
                if (item === key) {
                  tableAction.value[key] = true;
                  flag = false;
                  isHaveTableAction.value = true;
                }
              });
              if (flag) {
                tableAction.value[key] = false;
              }
            });

            tableData.value.forEach((_item, index) => {
              Object.keys(tableAction.value).forEach((key) => {
                tableData.value[index][key] = tableAction.value[key];
              });
            });
          }
        },
      });

      send(JSON.stringify(sendParams));
    },
    {
      immediate: true,
      deep: true,
    },
  );

  watch(
    () => props.widgetData,
    (nVal: any) => {
      if (nVal === undefined || nVal === null) {
        return;
      }
      nextTick(() => {
        setProps({
          title: nVal.formOption.tableTitle,
        });
      });

      if (nVal.tabletype === 'ENTITIES_TABLE') {
        Object.keys(tableAction.value).forEach((key) => {
          let flag = true;
          nVal.formOption.buttonFunction.forEach((item) => {
            if (item === key) {
              tableAction.value[key] = true;
              flag = false;
            }
          });
          if (flag) {
            tableAction.value[key] = false;
          }
        });

        tableData.value.forEach((_item, index) => {
          Object.keys(tableAction.value).forEach((key) => {
            tableData.value[index][key] = tableAction.value[key];
          });
        });
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  watch(
    () => props.isResize,
    () => {
      // resize();
    },
    {
      immediate: true,
    },
  );

  //是否全选
  const checkedKeys = ref<any>([]);

  // 表单内容 仓库
  onMounted(() => {
    //初始化 表格数据
    // 初始化边缘类型
    // getEdgeTypeDataList();
  });

  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: columns,
    ...tableStyleSetting,
    dataSource: tableData,
    canResize: true,
    maxHeight: 100,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除  '${checkedKeys.value.length}' 个边缘吗？`,
      content: '当心, 确认后，选定的边缘以及所有关联数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          // await deleteTheEdge(item);
        }
        checkedKeys.value = [];
        reload();
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }

  function handleMore(record: Recordable) {}
  // 删除
  async function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定删除边缘 名称${record.name} 吗？`,
      content: '当心, 确认后，边缘以及所有关联数据将不可恢复。',
      onOk: async () => {
        // await deleteTheEdge(record.id);
        reload();
      },
    });
  }
</script>
